import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart' as picker;
import 'package:management/const/consts.dart';
import 'package:management/const/init.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/project/request/ProjectConclusionRequestParams.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/generated/assets.dart';
import 'package:management/page/ModuleProject/project_detail_screen/logic.dart';
import 'state.dart';

class ProjectConclusionScreenLogic extends GetxController {
  final ProjectConclusionScreenState state = ProjectConclusionScreenState();

  @override
  void onInit() {
    super.onInit();
    _initData(false);
  }

  selectLegalPerson() {
    Get.bottomSheet(
        SizedBox(
          height: 500,
          child: Column(
            children: [
              SizedBox(
                height: 500,
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    return SizedBox(
                      height: 50,
                      child: ListTile(
                        leading: ClipOval(
                          child: FadeInImage(
                            image: NetworkImage(
                                state.listNumbers[index].avatar ??
                                    GlobalInit.headImage),
                            height: 45.w,
                            width: 45.h,
                            fit: BoxFit.fill,
                            placeholderFit: BoxFit.scaleDown,
                            placeholder: const AssetImage(Assets.iconAvator),
                          ),
                        ),
                        title: Text(
                          state.listNumbers[index].nickname ??
                              MyText.defaultName,
                          style: Theme.of(Get.context!).textTheme.titleSmall,
                        ),
                        subtitle: Text(
                          state.listNumbers[index].realName ??
                              MyText.defaultName,
                          style: Theme.of(Get.context!).textTheme.bodyMedium,
                        ),
                        onTap: () {
                          state.legalPersonUrl.value =
                              state.listNumbers[index].avatar ??
                                  GlobalInit.headImage;
                          state.legalPersonId.value =
                              state.listNumbers[index].id.toString();
                          Get.back();
                        },
                      ),
                    );
                  },
                  itemCount: state.listNumbers.length,
                ),
              ),
            ],
          ),
        ),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  selectApplyCompanyUser() {
    Get.bottomSheet(
        SizedBox(
          height: 500,
          child: Column(
            children: [
              SizedBox(
                height: 500,
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    return SizedBox(
                      height: 50,
                      child: ListTile(
                        leading: ClipOval(
                          child: FadeInImage(
                            image: NetworkImage(
                                state.listNumbers[index].avatar ??
                                    GlobalInit.headImage),
                            height: 45.w,
                            width: 45.h,
                            fit: BoxFit.fill,
                            placeholderFit: BoxFit.scaleDown,
                            placeholder: const AssetImage(Assets.iconAvator),
                          ),
                        ),
                        title: Text(
                          state.listNumbers[index].nickname ??
                              MyText.loading,
                          style: Theme.of(Get.context!).textTheme.titleSmall,
                        ),
                        subtitle: Text(
                          state.listNumbers[index].realName ??
                              MyText.loading,
                          style: Theme.of(Get.context!).textTheme.bodyMedium,
                        ),
                        onTap: () {
                          state.applyCompanyUserUrl.value =
                              state.listNumbers[index].avatar ??
                                  GlobalInit.headImage;
                          state.applyCompanyUserId.value =
                              state.listNumbers[index].id.toString();
                          Get.back();
                        },
                      ),
                    );
                  },
                  itemCount: state.listNumbers.length,
                ),
              ),
            ],
          ),
        ),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void addConclusionFiles() async {
    picker.FilePickerResult? result =
        await picker.FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: picker.FileType.custom,
      allowedExtensions: ['docx', 'pdf', 'doc', 'ppt', 'pptx', 'txt', 'md'],
    );

    if (result != null) {
      state.listConclusionPlatformFiles.value = result.files;
      state.listConclusionPlatformFiles.refresh();
    } else {
      Utils.toastError('File not found');
    }
  }

  void submit() {
    if (state.legalPersonId.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.legalPerson.tr}));
      return;
    }
    if (state.applyCompanyUserId.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.applyCompanyUser.tr}));
      return;
    }
    if (state.projectOutcome.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.projectOutcome.tr}));
      return;
    }
    _realSubmit();
  }

  Future<void> _realSubmit() async {
    LoadingElement.loadingDialog(true);
    List<dio.MultipartFile> conclusionFiles = state.listConclusionPlatformFiles
        .map((e) => dio.MultipartFile.fromFileSync(e.path!, filename: e.name))
        .toList();
    state.listConclusionFile.clear();
    await MyHttpClient.uploadFiles(conclusionFiles).then((value) {
      if (value.code == 200) {
        state.listConclusionFile.value = value.data!
            .map((e) => ConclusionFiles(filename: e.name, url: e.url))
            .toList();
      } else {
        Get.back();
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
      return;
    });
    var params = ProjectConclusionRequestParams(
        projectId: state.projectId,
        legalPersonId: int.parse(state.legalPersonId.value),
        applyCompanyUserId: int.parse(state.applyCompanyUserId.value),
        projectOutcome: state.projectOutcome.value,
        conclusionFiles: state.listConclusionFile);
    await MyHttpClient.projectConclusion(params).then((value) {
      if (value.code == 200) {
        Get.back();
        state.isConclusion.value = true;
        Get.find<ProjectDetailScreenLogic>().refreshProjectDetailPage();
        refreshProjectConclusionPage();
      } else {
        Get.back();
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
      return;
    });
  }

  void _initData(bool isRefresh) {
    MyHttpClient.getAllCompanyUser().then((value) {
      if (value.code == 200) {
        state.listNumbers.value = value.data!;
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
    refreshProjectConclusionPage();
  }

  void refreshProjectConclusionPage() {
    MyHttpClient.getConclusionProject(state.projectId.toString()).then((value) {
      if (value.code == 200) {
        state.isConclusion.value = value.data == null ? false : true;
        if (state.isConclusion.value) {
          state.conclusionDetail.value = value.data!;
        }
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }
}
